package com.ljqc.sbom.management.bean;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

import java.time.Instant;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Result<T> {
    private static final int SUCCESS_CODE = HttpStatus.OK.value();
    private static final int DEFAULT_ERR_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();
    private static final String DEFAULT_ERR_MSG = HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();

    /**
     * ===========================
     */
    private int code = SUCCESS_CODE;
    private String message = "ok";
    private T data = null;
    private final long timestamp = Instant.now().toEpochMilli();

    //****************静态方法们********************
    public static <T> Result<T> ok() {
        return new Result<>();
    }

    public static <T> Result<T> ok(T data) {
        Result<T> result = ok();
        result.setData(data);
        return result;
    }

    public static <T> Result<T> fail() {
        Result<T> result = new Result<>();
        result.setErrCode(DEFAULT_ERR_CODE);
        result.setErrMsg(DEFAULT_ERR_MSG);
        return result;
    }

    public static <T> Result<T> fail(int errCode, String errMsg) {
        Result<T> result = fail();
        result.setErrCode(errCode);
        result.setErrMsg(errMsg);
        return result;
    }

    /**
     * 判断是否成功
     *
     * @return true or false
     */
    public boolean isSuccess() {
        return getCode() == SUCCESS_CODE;
    }

    /**
     * 设置负载数据
     *
     * @param data 返回数据
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * 设置错误码
     *
     * @param errCode 错误码
     */
    public void setErrCode(int errCode) {
        if (errCode == SUCCESS_CODE) {
            throw new RuntimeException("Your code is " + errCode + ".Which only means SUCCESS");
        }
        this.code = errCode;
    }

    /**
     * 设置错误消息
     *
     * @param errMsg 错误消息
     */
    public void setErrMsg(String errMsg) {
        this.message = errMsg;
    }
}
